/* eslint-disable no-plusplus */
/* eslint-disable consistent-return */
/* eslint-disable no-param-reassign */
/* eslint-disable array-callback-return */
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import {
  getCustList,
  getSuppList,
  getContList,
  getContInfo,
  getCustInfo,
  getSuppInfo,
  getAreaList,
  gePdList,
  getInvTermList,
  getRuleDetail,
  updateSubmit,
  submit,
} from '@/services/invrule';
import { isRepeat, matchDict } from '@/utils/utils';

export default {
  state: {
    custList: [],
    suppList: [],
    custSuppType: '1', // 选择1客户 2供应商
    invRuleInfo: {},
    contList: [], // 合同列表
    invRulePanyTermMailDto: [], // 发票信息集合
    pdList: [], // 产品列表
    invList: [], // 发票信息列表
    MailList: [], // 邮寄地址列表
    invTermList: [], // 开票项目列表
    invMailData: [], // 发票抬头与邮寄地址数据
  },
  effects: {
    // 获取模糊查询客户列表：有效客户
    *fetchCustSuppList({ payload }, { call, put }) {
      const custResponse = yield call(getCustList, { name: payload });
      const suppResponse = yield call(getSuppList, { name: payload });
      yield put({
        type: 'updateModelData',
        payload: {
          custList: [],
          suppList: [],
        },
      });
      if (custResponse.success && suppResponse.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            custList: Array.isArray(custResponse.data) ? custResponse.data : [],
            suppList: Array.isArray(suppResponse.data) ? suppResponse.data : [],
          },
        });
      } else {
        message.warning(
          `${custResponse.message || suppResponse.message || '获取客户与供应商数据：服务端错误'}`
        );
      }
    },
    // 获取合同列表
    *fetchContList(
      {
        payload: { custSuppType, custSuppId, serType },
      },
      { call, put, select }
    ) {
      const response = yield call(getContList, { custSuppType, custSuppId, serType });
      const { SER_TYPE } = yield select(state => state.publicdata.dictCode);
      yield put({
        type: 'updateModelData',
        payload: {
          contList: [],
        },
      });
      if (response.success) {
        if (response.data && response.data.length) {
          yield put({
            type: 'updateModelData',
            payload: {
              contList: response.data,
            },
          });
        } else {
          message.warning(
            `${response.message ||
              `该${custSuppType === '1' ? '客户' : '供应商'}在服务类型为‘${matchDict(
                SER_TYPE,
                serType
              )}’下未关联合同信息！`}`
          );
        }
      } else {
        message.warning(response.message || '获取合同数据：服务端错误');
      }
    },
    // 根据合同获取是否全额计税
    *fetchContInfo({ payload }, { call, put }) {
      const response = yield call(getContInfo, payload);
      yield put({
        type: 'updateRuleInfo',
        payload: {
          fullyFlag: '1',
          fullyFlagName: '--',
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateRuleInfo',
          payload: {
            fullyFlag: response.data.crmCustContConfig && response.data.crmCustContConfig.fullyFlag,
            fullyFlagName:
              response.data.crmCustContConfig && response.data.crmCustContConfig.fullyFlag === 1
                ? '是'
                : '否',
          },
        });
      } else {
        message.warning(response.message || '获取合同数据：服务端错误');
      }
    },
    // 获取发票或者邮寄地址数据
    *fetchInvOrMailInfo(
      {
        payload: { custSuppId, custSuppType, sysCode },
      },
      { call, put }
    ) {
      yield put({
        type: 'setInvOrMailList',
        payload: {
          invList: [],
          MailList: [],
        },
      });
      const response = yield call(
        custSuppType === '1' ? getCustInfo : getSuppInfo,
        custSuppType === '1' ? { custId: custSuppId } : { suppId: custSuppId }
      );
      if (response.success && response.data) {
        const { data } = response;
        yield put({
          type: 'setInvOrMailList',
          payload: {
            invList: custSuppType === '1' ? data.invoiceList : data.suppInvoiceList,
            MailList: custSuppType === '1' ? data.mailAddrList : data.suppMailAddrList,
          },
        });
      } else {
        message.warning(
          `${response.message ||
            `获取${
              // eslint-disable-next-line no-nested-ternary
              sysCode === 2 ? '签约方' : custSuppType === '1' ? '客户' : '供应商'
            }信息：服务端错误！`}`
        );
      }
      return response;
    },
    // 获取省市区列表
    *getAreaList({ payload }, { call }) {
      const response = yield call(getAreaList, payload);
      if (response.success) {
        return response;
      }
      message.warning(response.message || '获取地区数据：服务端错误');
      return false;
    },
    // 根据产品列表
    *fetchPdList({ payload }, { call, put }) {
      const response = yield call(gePdList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          pdList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            pdList: response.data,
          },
        });
      } else {
        message.warning(response.message || '获取产品列表数据：服务端错误');
      }
    },
    // 根据开票项目列表
    *fetchInvTermList(
      {
        payload: { id, key, serType, pdId, bilingType },
      },
      { call, put }
    ) {
      const response = yield call(getInvTermList, { serType, pdId, bilingType });
      if (response.success && response.data) {
        yield put({
          type: 'setRuleDto',
          payload: {
            targetKey: 'invTermList',
            parentKey: 'invTerm',
            value: response.data,
            id,
            key,
          },
        });
      } else {
        message.warning(response.message || '获取开票项目数据：服务端错误');
      }
    },
    // 获取修改回显数据
    *fetchUpdateInfo({ payload }, { call, put, select }) {
      const response = yield call(getRuleDetail, payload);
      const { invList, pdList, MailList } = yield select(state => state.editinvrule);
      const { FM_INV_RULE_WAY } = yield select(state => state.publicdata.dictCode);
      if (response.success) {
        const {
          custSuppId,
          custSuppName,
          contId,
          contName,
          invType,
          invTypeName,
          serType,
          serTypeName,
          invQuota,
          fullyFlag = '2',
          fullyFlagName = '否',
          invRulePanyTermMailDto,
          custSuppType,
        } = response.data;
        if (invRulePanyTermMailDto && invRulePanyTermMailDto.length) {
          invRulePanyTermMailDto.map((item, index) => {
            item.id = item.invCompany && item.invCompany.invType;
            item.invList = invList;
            item.pdList = pdList;
            item.MailList = MailList;
            item.tableId = index;
            item.invType =
              item.invCompany && item.invCompany.invType && `${item.invCompany.invType}`;
            if (item.invMail && item.invMail.invPay) {
              const sortNumber = (a, b) => b.itemCode - a.itemCode; // 大于到小)
              if (item.invMail.invPay === 3) {
                // 电子邮件
                item.invMail.invPayList = FM_INV_RULE_WAY.sort(sortNumber).filter(
                  d => d.itemCode === '3'
                );
              } else {
                item.invMail.invPayList = FM_INV_RULE_WAY.sort(sortNumber).filter(
                  d => d.itemCode !== '3'
                );
                if (
                  item.invMail.invPay === 1 &&
                  item.invMail.areaList &&
                  item.invMail.areaList.length
                ) {
                  const areaIdList = [];
                  item.invMail.areaList.forEach(a => {
                    areaIdList.push(a.areaId);
                  });
                  item.invMail.mailArea = areaIdList;
                }
              }
            }
            if (item.invCompany && item.invCompany.invType) {
              item.invCompany.invType = `${item.invCompany.invType}`;
            }
            if (item.invTerm && item.invTerm.length) {
              item.invTerm.map(c => {
                c.id = item.id;
                c.key = c.pdId;
                c.pdList = pdList;
                c.invTermList = [{ termId: c.invTerm, invTerm: c.invTermName }];
              });
            }
          });
        }
        yield put({
          type: 'updateModelData',
          payload: {
            invRuleInfo: {
              ...response.data,
              custSuppId,
              custSuppName,
              contId,
              contName,
              invType: `${invType}`,
              invTypeName,
              serType: `${serType}`,
              serTypeName,
              invQuota,
              fullyFlag: `${fullyFlag}`,
              fullyFlagName,
              custSuppType: `${custSuppType}`,
            },
            invRulePanyTermMailDto,
          },
        });
        return response.data;
      }
      message.warning(`${response.message || '获取规则数据：服务端错误！'}`);
    },
    // 提交数据
    *submit(
      {
        payload: { values, invRuleId, isUpdate, sysCode },
      },
      { call, put, select }
    ) {
      const { FM_INV_RULE_TYPE } = yield select(state => state.publicdata.dictCode);
      const { invRulePanyTermMailDto, custSuppType } = yield select(state => state.editinvrule);
      let submitData = { custSuppType, contNo: sysCode === 2 ? '3' : custSuppType };
      Object.entries(values).forEach(([key, value]) => {
        if (key === 'invQuota') {
          // eslint-disable-next-line no-unused-expressions
          submitData[key] = value === 0 ? 0 : (value && parseFloat(value)) || null;
        } else if (!value && key !== 'invQuota') {
          submitData[key] = null;
        } else if (value.key) {
          submitData[key] = value.key;
        } else if (key === 'invRulePanyTermMailDto') {
          value = value.filter(item => item);
          if (
            (values.invType && values.invType.key === '4') ||
            (values.invType && values.invType.key === '5')
          ) {
            value = JSON.parse(JSON.stringify(value.reverse()));
          }
          for (let index = 0; index < value.length; index++) {
            const item = value[index];
            if (item.invTerm) {
              if (Array.isArray(item.invTerm)) {
                item.invTerm = item.invTerm.filter(c => c);
              } else {
                // eslint-disable-next-line compat/compat
                item.invTerm = Object.values(item.invTerm);
              }
              item.invTerm = item.invTerm.map(t => ({
                ...t,
                invRatio: t.invRatio === 0 ? 0 : (t.invRatio && parseFloat(t.invRatio)) || null,
              }));
              if (isRepeat(item.invTerm, 'pdId')) {
                message.warning(
                  `发票类型为'${item.invCompany &&
                    matchDict(
                      FM_INV_RULE_TYPE,
                      `${item.invCompany.invType}`
                    )}'下产品重复，请重新选择！`
                );
                return;
              }
            }
            if (
              invRulePanyTermMailDto[index].invMail &&
              invRulePanyTermMailDto[index].invMail.invPay !== '2' &&
              invRulePanyTermMailDto[index].invMail.mailArea
            ) {
              if (invRulePanyTermMailDto[index].invMail.mailArea.length < 2) {
                return message.warning(
                  `发票类型为'${item.invCompany &&
                    matchDict(
                      FM_INV_RULE_TYPE,
                      item.invCompany.invType
                    )}'下邮寄地址选择不完整，请重新选择！`
                );
              }
              item.invMail.mailArea =
                invRulePanyTermMailDto[index].invMail.mailArea[
                  invRulePanyTermMailDto[index].invMail.mailArea.length - 1
                ];
            }
            submitData[key] = value;
          }
        } else {
          submitData[key] = value;
        }
      });
      if (!submitData.invRulePanyTermMailDto) return;
      submitData = invRuleId
        ? (isUpdate && { ...submitData, invRuleId }) || submitData
        : submitData;
      const response = yield call(
        invRuleId ? (isUpdate && updateSubmit) || submit : submit,
        submitData
      );
      if (response.success) {
        message.success(invRuleId ? '保存成功!' : '新增成功！');
        yield put(
          routerRedux.push({
            pathname: '/fmmanage/invoice/index',
          })
        );
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    getCustList(state, { payload }) {
      return {
        ...state,
        custList: payload,
      };
    },
    getSuppList(state, { payload }) {
      return {
        ...state,
        supplyList: payload,
      };
    },
    // 设置修改规则信息数据
    updateRuleInfo(state, { payload }) {
      const { invRuleInfo } = state;
      return {
        ...state,
        invRuleInfo: {
          ...invRuleInfo,
          ...payload,
        },
      };
    },
    // 选择发票类型
    selectInvType(
      state,
      {
        payload: { invType, invTypeName, invPayList },
      }
    ) {
      const { invRuleInfo, pdList, invList, MailList } = state;
      const invRulePanyTermMailDto = [];
      const invTypeList = invTypeName.split('+');
      invTypeList.forEach(item => {
        const invCompany = {
          // 发票抬头
          invType,
        };
        const invMail = {
          // 邮寄信息
          invPay: '2',
        };
        invCompany.invTypeName = item;
        if (item === '专票(服务费)') {
          invCompany.invType = '3';
        } else if (item === '纸质普票(代收代付)') {
          invCompany.invType = '1';
        } else if (item === '电子普票(代收代付)') {
          invCompany.invType = '2';
        }
        const sortNumber = (a, b) => b.itemCode - a.itemCode; // 大于到小)
        if (item === '电子普票' || item === '电子普票(代收代付)') {
          invMail.invPayList = invPayList.sort(sortNumber).filter(d => d.itemCode === '3');
          invMail.invPay = '3';
        } else {
          invMail.invPayList = invPayList.sort(sortNumber).filter(d => d.itemCode !== '3');
          invMail.invPay = '2';
        }

        invRulePanyTermMailDto.push({
          id: invCompany.invType,
          invCompany,
          invList,
          tableId: 0,
          invTerm: [
            {
              id: invCompany.invType,
              key: 0,
              pdList,
              invTermList: [],
              pdId: undefined,
              bilingType: undefined,
              invTerm: undefined,
              invRatio: undefined,
            },
          ],
          pdList,
          invMail,
          MailList,
        });
      });
      return {
        ...state,
        invRulePanyTermMailDto,
        invRuleInfo: {
          ...invRuleInfo,
          invType,
          invTypeName,
        },
      };
    },
    // 跟新发票或者邮寄地址弹框信息
    updateInvOrMailList(
      state,
      {
        payload: { invMailType, invMailId },
      }
    ) {
      const { invList, MailList } = state;
      return {
        ...state,
        invMailId,
        invMailType,
        invMailData: invMailType === '1' ? invList : MailList,
      };
    },
    // 重置发票或者邮寄地址弹框信息
    setInvOrMailList(
      state,
      {
        payload: { invList, MailList },
      }
    ) {
      const { invRulePanyTermMailDto } = state;
      invRulePanyTermMailDto.map(item => {
        item.invList = invList;
        item.MailList = MailList;
      });
      return {
        ...state,
        invList,
        MailList,
        invRulePanyTermMailDto,
      };
    },
    // 重置发票或者邮寄地址信息
    resetInvOrMailInfo(state) {
      const { invRulePanyTermMailDto } = state;
      invRulePanyTermMailDto.map(item => {
        Object.keys(item.invCompany).forEach(key => {
          if (key !== 'invType' && key !== 'invTypeName' && key !== 'remark') {
            delete item.invCompany[key];
          }
        });
        Object.keys(item.invMail).forEach(key => {
          if (key !== 'invPay' && key !== 'invPayName' && key !== 'email' && key !== 'invPayList') {
            delete item.invMail[key];
          }
          if (key === 'invPay') {
            item.invMail[key] = '2';
          }
        });
      });
      return {
        ...state,
        invRulePanyTermMailDto,
      };
    },

    // 确定选择的发票或邮寄地址信息
    saveInvOrMail(
      state,
      {
        payload: { invMailId, invMailType, invOrMailInfo },
      }
    ) {
      const { invRulePanyTermMailDto } = state;
      invRulePanyTermMailDto.map(item => {
        if (item.id === invMailId) {
          if (invMailType === '1') {
            // 发票抬头
            item.invCompany = { ...item.invCompany, ...invOrMailInfo };
          } else {
            // 邮寄地址
            item.invMail = { ...item.invMail, ...invOrMailInfo };
          }
        }
      });
      return {
        ...state,
        invRulePanyTermMailDto,
      };
    },
    // 设置规则抬头发票信息
    setRuleDto(
      state,
      {
        payload: { targetKey, parentKey, value, id, key }, // 当前变量 父对象字段 值 当前数据id  设置表格数据id
      }
    ) {
      const { invRulePanyTermMailDto } = state;
      invRulePanyTermMailDto.map(item => {
        if (item.id === id) {
          if ((key === 0 || key) && item[parentKey].length) {
            // 设置表格发票项目数据
            item[`${parentKey}`].map(c => {
              if (c.key === key) {
                c[targetKey] = value;
              }
            });
          } else {
            // 设置发票，邮寄等数据
            item[parentKey][targetKey] = value;
          }
        }
      });
      return {
        ...state,
        invRulePanyTermMailDto,
      };
    },
  },
};
